<?php
/**
 * @package		yos_showcase
 * @subpackage	Components
 * @link		http://yopensource.com
 * @author		yopensource
 * @copyright 	yopensource (yopensource@gmail.com)
 * @license		Commercial
 */
// Check to ensure this file is included in Joomla!
defined('_JEXEC') or die();

jimport('joomla.filesystem.file');

require_once(JPATH_COMPONENT_SITE.DS.'helpers'.DS.'phpWebHacks.php');

/**
 * Yos Utility class
 * Store many useful functions
 *
 */
class Yos_translator extends JObject 
{

	/**
	 * Do Translate
	 *
	 * @param string $languagePair
	 * @param string $string_in want to translate
	 * @return string translated
	 */
	function translate($languagePair, $string_in) {
		
		global $option;
		
		$str_out = '';
		
		$content = $this->replace_chars_encode($string_in);
		
		//links url processing, add yos_link_begin before and yos_link_end after link url
		preg_match_all('/<a(.*?)href="(.*?)"/i', $content, $matches);
		for($i = 0; $i < count($matches[0]); $i++){
			$content = str_replace($matches[0][$i], '<a'.$matches[1][$i].'yos_link_begin'.base64_encode($matches[2][$i]).'yos_link_end ', $content);
		}
		
		//span tag processing, replace <span by <yos_span and </span by </yos_span
		$content	= preg_replace('/<span/i', '<yos_span', $content);
		$content	= preg_replace('/<\/span/i', '</yos_span', $content);

		//code tag processing, replace <code by <yos_code and </code by </yos_code
		$content	= preg_replace('/<code/i', '<yos_code', $content);
		$content	= preg_replace('/<\/code/i', '</yos_code', $content);
		
		//create a header
		$header		=	 "<!DOCTYPE html PUBLIC '-//W3C//DTD XHTML 1.0 Transitional//EN' 'http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd'>"
						."<html xmlns='http://www.w3.org/1999/xhtml'>"
						."<head>"
						."<meta http-equiv='Content-Type' content='text/html; charset=UTF-8'/>"
						."<title>Yos Translator</title>"
						."</head>"
						."<body>";
		
		//create footer
		$footer		= 	 "</body>"
						."</html>";
		
		$yos_file	=	$header.$content.$footer;
				
		//BEGIN write file: write this content to a file
		$clock		= md5(time().uniqid(''));
		$file		= JPATH_SITE.DS.'tmp'.DS."yos_page_".$clock.".html";
		JFile::write($file, $yos_file);
		//END write file
		
		$browser = new phpWebHacks();
		
		//BEGIN building url to connect
		$lang_trans	= explode('|', $languagePair);
		$hl			= $lang_trans[0];
		$sl			= $lang_trans[0];
		$tl			= $lang_trans[1];		
		$u			= JURI::root()."tmp/yos_page_".$clock.".html";
		//END building url to connect
				
		$url = "http://translate.google.com/translate?hl=".$hl."&sl=".$sl."&tl=".$tl."&u=".$u;
		$result = $browser->get($url);
		if (!$result) {
			$this->setError("ERROR #01: could not get ".$url);
			return false;
		}
		
		//get the second frame
		if (!preg_match('/<frame src="(\/translate_p.*?usg=.*?)"/i', $result, $match)) {
			$this->setError("ERROR #02: couldn't get second frame");
			return false;
		}
		$hostName = 'translate.google.com';
		$directory = preg_replace('/&amp;/', '&', $match[1]);
		
		$url2 = "http://translate.google.com/$directory";
		$result = $browser->get($url2);
		if (!$result) {
			$this->setError("ERROR #03: could not get ".$url2);
			return false;
		}
						
		//Remove cache file
		JFile::delete($file);
		
		/*
		//get return encoding preg_match('/charset=(.*?)\sDate/', $result, $encoding);
		preg_match('/charset=(.*?)\s/', $result, $encoding);
		$convert = 0;
		if(!isset($encoding[1]))
		{
			$convert=1;
			return "ERROR #06: Google return invalid value <br /> ".htmlspecialchars($result);
		}	
		//encode utf-8
		if($convert ==0){
			$encoding_begin		= substr($encoding[1], 0, strlen($encoding[1])-1);
			$encoding_to		= "UTF-8";
			$result 			= mb_convert_encoding($result, $encoding_to, $encoding_begin);
		}
		*/

		//get content in body
		preg_match('/<body(.*?)>(.*)<\/html>/ism', $result, $match);
		$content_in	= $match[2];
		
		$content_in = preg_replace('/<\/body>/ism', '', $content_in);
		
		//remove google iframe
		$content_in = preg_replace('/<iframe\s.*?src="http:\/\/translate\.google\.com.*?".*?><\/iframe>/ism', '', $content_in);
		
		//remove tipon and tipoff span
		preg_match_all('/<span\s+.*?tipon.*?tipoff.*?><span\s+.*?class="google-src-text".*?>.*?<\/span>(.*?)<\/span>/ism', $content_in, $matches);
		for ($i = 0; $i < count($matches[0]); $i++){
			$content_in	= str_replace($matches[0][$i], $matches[1][$i], $content_in);
		}
		
		//remove _addload script
		$content_in = preg_replace('/<script>_addload\(function\(\).*?<\/script>/ism', '', $content_in);
				
		//return valid link url
		preg_match_all('/yos_link_begin(.*?)yos_link_end/ism', $content_in, $matches);
		for ($i = 0; $i < count($matches[0]); $i++){
			$content_in = str_replace($matches[0][$i], ' href="'.base64_decode($matches[1][$i]).'" ', $content_in);
		}		
		
		//remove all </span tags
		$content_in	= str_replace('</span>','',$content_in);
		
		//replace <yos_span and </yos_span by <span and </span
		$content_in = str_replace('<yos_span', '<span', $content_in);
		$content_in = str_replace('</yos_span', '</span', $content_in);

		//code tag processing, replace <yos_code by <code and </yos_code by </code
		$content_in	= preg_replace('/<yos_code/i', '<code', $content_in);
		$content_in	= preg_replace('/<\/yos_code/i', '</code', $content_in);
		
		
		$content_trans	= rawurldecode($content_in);
		$content_trans 	= preg_replace_callback('/&#\d{2,5};/smu', array(&$this,"utf8_entity_decode"), $content_trans );
		
		$str_out = $this->restore_chars_encode($content_trans);

		//using tidy to clean html code
		if( function_exists( 'tidy_parse_string' ) ) {
			//find and replace empty <div>
			$str_out = preg_replace('/<div>\s*<\/div>/smu', '<div>&nbsp;</div>', $str_out);
			//var_dump(htmlspecialchars($str_out));echo '<hr />';
			$config = array(
				'indent' => TRUE, 
				'output-xhtml' => TRUE,
				'wrap' => 0
                );
			$tidy = tidy_parse_string($str_out, $config, 'utf8');
			$tidy->cleanRepair();
			$str_out = $tidy;
			
			//get content in body
			preg_match('/<body(.*?)>(.*)<\/html>/ism', $str_out, $match);
			$str_out	= $match[2];
		
			$str_out = preg_replace('/<\/body>/ism', '', $str_out);
			//restore empty div
			$str_out = preg_replace('/<div>\s*&nbsp;\s*<\/div>/smu', '<div></div>', $str_out);
			//var_dump(htmlspecialchars($str_out));die();
		}
		
		return $str_out;
	}
	
	function replace_chars_encode($text)
	{
		$patterns[00]		= '/{/';
		$patterns[01]		= '/}/';
		$replacements[00]	= 'mmdd0000';
		$replacements[01]	= 'mmdd0001';
		$text=preg_replace($patterns, $replacements, $text);
		
		return $text;
	}
		
	function restore_chars_encode($text)
	{
		$patterns[00]		= '/mmdd0000/';
		$patterns[01]		= '/mmdd0001/';
		$replacements[00]	= '{';
		$replacements[01]	= '}';
		$text=preg_replace($patterns, $replacements, $text);
		
		return $text;
	}
	
	
	function utf8_entity_decode($entity)
	{
		$convmap = array(0x0, 0x10000, 0, 0xfffff);
		return mb_decode_numericentity($entity[0], $convmap, 'UTF-8');
	}
}

